<template>
  <Dialog v-model="dialogVisible" title="上传文件">
    <el-row> 
      <el-col :span="24">
        <el-upload
ref="uploadRef" v-model:file-list="fileList" :action="uploadUrl" :auto-upload="false" :data="data"
          :disabled="formLoading" :limit="1" :on-change="handleFileChange" :on-error="submitFormError"
          :on-exceed="handleExceed" :on-success="submitFormSuccess" :http-request="httpRequest" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-red!">
              每次只能上传 1 个文件，新文件将覆盖旧文件!
            </div>
          </template> 
        </el-upload>
      </el-col> 
      <el-col :span="24" class="mt-10px">
        <el-input v-if="fileList.length>0" v-model="data.title" placeholder="请给设置备注名称">
          <template #prepend>文件备注名称</template>
        </el-input>
      </el-col>
    </el-row> 
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
defineOptions({ name: 'InfraFileForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const props = defineProps<{ parentId?: number }>()
const data = ref({ path: '', parentId: props.parentId || 0 ,title:''})
const uploadRef = ref<UploadInstance>()

const { uploadUrl, httpRequest } = useUpload()

/** 打开弹窗 */
const open = async (parentId?: number) => {
  dialogVisible.value = true
  resetForm()
  // 直接整体赋值，确保el-upload能感知到变化
  data.value = { path: '', parentId: parentId ?? 0,title:'' }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
  data.value.title = file.name // 设置默认备注名称为文件名
}

/** 提交表单 */
const submitFileForm = () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 关键：每次提交前都整体赋值一次
  data.value = { ...data.value, parentId: props.parentId || data.value.parentId || 0, title:data.value.title || ''}
  // message.alert(data.value.parentId + '')
  unref(uploadRef)?.submit()
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = () => {
  // 清理
  dialogVisible.value = false
  formLoading.value = false
  unref(uploadRef)?.clearFiles()
  // 提示成功，并刷新
  message.success(t('common.createSuccess'))
  emit('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
// const handleExceed = (): void => {
//   message.error('最多只能上传一个文件！')
// }
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}
</script>
